﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;

namespace WeChatWebAPI.Controllers
{
    public class WeChatController : ApiController
    {
        // GET api/wechat
        public HttpResponseMessage Get(string echoStr, string signature, string timestamp, string nonce)
        {
            var client = new WeChatService.AuthServiceClient();

            client.Auth(new WeChatService.AuthInfo()
            {
                Echostr = echoStr,
                Nonce = nonce,
                Signature = signature,
                Timestamp = timestamp
            });

            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(echoStr, Encoding.UTF8);
            response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                MaxAge = TimeSpan.FromMinutes(20)
            };

            return response;
        }

        // POST api/wechat
        public HttpResponseMessage Post(HttpRequestMessage request)
        {
            var client = new WeChatService.ReceiveMessageServiceClient();

            client.ReceiveRawMessage("\r\n-------URL---------\r\n" + request.RequestUri.ToString() + "\r\n---------PostData-------\r\n" + request.Content.ReadAsStringAsync().Result);

            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent("", Encoding.UTF8);
            response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                MaxAge = TimeSpan.FromMinutes(20)
            };

            return response;
        }
    }
}